<?php
#
# VERSION
#
define('EXPORT_VERSION', '1.0');
define('EXPORT_AUTHOR', 'Petko D. (pdp) Petkov');
define('EXPORT_AUTHOR_HOMEPAGE', 'http://www.gnucitizen.org/about/pdp');

#
# PARAMETERS
#
$PARAMS = array_merge($_GET, $_POST);

#
# HELPERS
#
function is_assoc($php_val) {
	return is_array($php_val) && array_keys($php_val) !== range(0, sizeof($php_val) - 1);
}

function to_json($php_val) {
	if (is_assoc($php_val)) {
		$tmp = array();

		foreach ($php_val as $key => $val) {
			$tmp[] = to_json($key).':'.to_json($val);
		}

		return '{'.join($tmp, ',').'}';
	} else if (is_array($php_val)) {
			$tmp = array();

			foreach ($php_val as $val) {
				$tmp[] = to_json($val);
			}

			return '['.join($tmp, ',').']';
	} else if (is_object($php_val)) {
		return to_json(get_object_vars($php_val));
	} else if (is_string($php_val)) {
		return "'".str_replace(array("\b", "\t", "\n", "\f", "\r", "'"), array('\b', '\t', '\n', '\f', '\r', "\'"), stripslashes($php_val))."'";
	} else if (is_bool($php_val)){
		return $php_val?'true':'false';
	} else if (!isset($php_val)) {
		return 'undefined';
	} else {
		return $php_val;
	}
}

#
# EXPORTERS
#
function export_raw($php_val) {
	header('Content-type: text/plain');

	echo $php_val;
}

function export_php($php_val) {
	header('Content-type: text/plain');

	print_r($php_val);
}

function export_json($php_val) {
	global $PARAMS;

	header('Content-type: text/javascript');

	if (isset($PARAMS['_callback'])) {
		echo $PARAMS['_callback'].'('.to_json($php_val).');';
	} else {
		echo to_json($php_val);
	}
}

function export_serialized($php_val) {
	header('Content-type: text/plain');

	echo serialize($php_val);
}

#
# EXPORT
#
function export($php_val) {
	global $PARAMS;

	if (isset($PARAMS['_output']) && function_exists('export_'.$PARAMS['_output'])) {
		call_user_func('export_'.$PARAMS['_output'], $php_val);
	} else {
		call_user_func('export_json', $php_val);
	}
}
